package ch.pizzapp.kurier.adapter;

import java.util.List;

import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.RootContext;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import ch.pizzapp.kurier.data.OrderItemData;
import ch.pizzapp.kurier.view.OrderItem;
import ch.pizzapp.kurier.view.OrderItem_;

@EBean
public class OrderAdapater extends BaseAdapter {
	List<OrderItemData> orderItemList;

	@RootContext
	Context context;

	Callback mCallback;

	public void setOnCallback(Callback mCallback) {
		this.mCallback = mCallback;
	}

	public void clearData() {
		// clear the data
		if (orderItemList != null) {
			orderItemList.clear();
		}
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		int size = 0;
		if (orderItemList != null) {
			size = orderItemList.size();
		}

		return size;

	}

	public List<OrderItemData> getOrderItemList() {
		return orderItemList;
	}

	public void setOrderItemList(List<OrderItemData> orderItemList) {
		this.orderItemList = orderItemList;
	}

	@Override
	public OrderItemData getItem(int position) {
		return orderItemList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return Long.valueOf(orderItemList.get(position).getItemID());
	}

	public interface Callback {
		void onClicked(int selectQuentityValue, Double calculatedValue,
				Integer itemId);

		void deleteFromCart(OrderItemData orderItemData);

	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		OrderItem orderItem;
		if (convertView == null) {
			orderItem = OrderItem_.build(context);
		} else {
			orderItem = (OrderItem) convertView;
		}

		orderItem.bind(getItem(position));

		orderItem.setOnCallBack(new OrderItem.Callback() {

			@Override
			public void deleteFromCart() {
				// TODO Auto-generated method stub
				if (mCallback != null) {
					mCallback.deleteFromCart(getItem(position));
				}

			}

			@Override
			public void onClicked(int selectQuentityValue,
					Double calculatedValue, Integer itemId) {
				// TODO Auto-generated method stub

				getItem(position).setQuentity(selectQuentityValue);
				getItem(position).setPrice(calculatedValue);
				if (mCallback != null) {
					mCallback.onClicked(selectQuentityValue, calculatedValue,
							itemId);
				}

			}

			// @Override
			// public void addToCart() {
			// // TODO Auto-generated method stub
			// System.out.println("addToCart");
			// if (mCallback != null) {
			// mCallback.addToCart(getItem(position));
			// }
			// }
			//
			// @Override
			// public void onClicked(int quentity, int selectedSizeIndex,
			// Double price) {
			// // TODO Auto-generated method stub
			//
			// getItem(position).setQuentity(quentity);
			//
			// getItem(position).setCalculatedValue(price);
			//
			// getItem(position).setSelectedSizeIndex(selectedSizeIndex);
			//
			// }
		});

		return orderItem;

	}

}
